package EncryptionTool

import (
	"crypto/aes"
	"crypto/cipher"
	"crypto/rand"
	"encoding/base64"
)

func AseEncrypt(data, key string) (string, error) {

	block, err := aes.NewCipher([]byte(key))
	if err != nil {
		return "", err
	}

	encrypted := make([]byte, aes.BlockSize+len(data))
	iv := encrypted[:aes.BlockSize]
	if _, err := rand.Read(iv); err != nil {
		return "", err
	}

	cipher.NewCFBEncrypter(block, iv).XORKeyStream(encrypted[aes.BlockSize:], []byte(data))

	return base64.StdEncoding.EncodeToString(encrypted), nil
}

func AesDecrypt(data, key string) (string, error) {
	// 解码 Base64 密文
	encrypted, err := base64.StdEncoding.DecodeString(data)
	if err != nil {
		return "", err
	}

	// 使用相同的密钥初始化 AES 块
	block, err := aes.NewCipher([]byte(key))
	if err != nil {
		return "", err
	}

	// 提取初始向量
	iv := encrypted[:aes.BlockSize]

	// 创建 CFB 解密器
	stream := cipher.NewCFBDecrypter(block, iv)

	// 解密数据
	stream.XORKeyStream(encrypted[aes.BlockSize:], encrypted[aes.BlockSize:])

	// 返回解密后的明文
	return string(encrypted[aes.BlockSize:]), nil
}

/*
php语言加密解密代码如下：

function AesDecrypt($data, $key) {
    $data = base64_decode($data);
    $iv = substr($data, 0, 16);
    $encrypted = substr($data, 16);

    $decrypted = openssl_decrypt($encrypted, 'aes-256-cfb', $key, OPENSSL_RAW_DATA, $iv);

    return $decrypted;
}

function AesEncrypt($data, $key) {
    $ivLength = openssl_cipher_iv_length('aes-256-cfb');
    $iv = openssl_random_pseudo_bytes($ivLength);

    $encrypted = openssl_encrypt($data, 'aes-256-cfb', $key, OPENSSL_RAW_DATA, $iv);

    $result = base64_encode($iv . $encrypted);

    return $result;
}

javascript加密解密代码如下:
<script src="./crypto-js.min.js"></script>
<script>
    var iv_str=(Math.random().toString(36).substr(2, 16)+"0123456789012345").substr(0, 16)
    // 导入crypto-js库
    function aesEncrypt(data, key) {
        var iv = CryptoJS.enc.Utf8.parse(iv_str); //偏移16为
        var encrypted = CryptoJS.AES.encrypt(iv_str+data, key, {
            iv: iv,
            mode: CryptoJS.mode.CFB,
            padding: CryptoJS.pad.Pkcs7
        });
        return encrypted.toString();
    }

    function aesDecrypt(encryptedData, key) {
        var iv = CryptoJS.enc.Utf8.parse(iv_str); //偏移16为
        var bytes  = CryptoJS.AES.decrypt(encryptedData, key, {
            iv: iv,
            mode: CryptoJS.mode.CFB,
            padding: CryptoJS.pad.Pkcs7,
        });
        var originalText = bytes.toString(CryptoJS.enc.Utf8);
        return originalText.slice(16);
    }

    var key = '01234567890123456789012345678901';
    key=CryptoJS.enc.Utf8.parse(key)
    var data = 'nihaoyuangaowoshichenjinliang';
    var encryptedData = aesEncrypt(data, key);
    console.log(encryptedData); // 输出加密后的数据
    console.log(aesDecrypt(encryptedData,key)) // 输出解密后的数据

</script>

*/
